<template>
  <div class="app-container">
    <!-- 条件栏 -->
    <div class="filter-wrapper">
      <NewPageFilter
        v-model:query="filterInfo.query"
        :filter-list="filterInfo.list"
        :filter-btn="filterInfo.btn"
      >
      </NewPageFilter>
    </div>
    <div class="filter-wrapper">
      <NewPageFilter :filter-btn="filterInfo.btnList">
        <template v-slot:filter-del>
          <el-button :disabled="!canDelete" @click="del()">删除</el-button>
        </template>
      </NewPageFilter>
    </div>
    <!-- 表格 -->
    <TableContainer
      :refresh="tableInfo.refresh"
      :init-curpage="tableInfo.initCurpage"
      v-model:data="tableInfo.data"
      :api="tableInfo.api"
      :query="filterInfo.query"
      :tab-index="true"
      :field-list="tableInfo.fieldList"
      :pager="true"
      :checkBox="false"
      :handle="tableInfo.handle"
      @handleEvent="handleEvent"
    >
    </TableContainer>
    <!-- S 新增权限组抽屉组件 -->
    <AddGroup
      v-if="drawer"
      :drawer="drawer"
      :currentSetp="currentSetp"
      :currentGroup="currentGroup"
      @close="addGroupClose"
      @refresh="refresh"
      @refreshList="refreshList"
    ></AddGroup>
    <!-- E 新增权限组抽屉组件 -->

    <!-- S 编辑弹窗组件 -->
    <EditGroupDialog
      v-if="groupOpen"
      ref="cateDialog"
      :formObj="formObj"
      :open="groupOpen"
      @close="groupClose"
      @submit="confirmBtn"
    ></EditGroupDialog>
    <!-- E 编辑弹窗组件 -->
    <!-- S 文档目录弹窗组件 -->
    <DocCateDialog
      v-if="cateOpen"
      ref="docCateDialog"
      :open="cateOpen"
      :groupList="groupList"
      :groupTree="groupTree"
      :groupTreeCheck="groupTreeCheck"
      @checkChange="_checkChange"
      @close="cateClose"
      @submit="confirmBtnCate"
    ></DocCateDialog>
    <!-- E 文档目录弹窗组件 -->
    <!-- S 关联人员弹窗组件 -->
    <AuthorizedOfficerDialog
      v-if="prsonOpen"
      ref="documentCategoryDialog"
      :open="prsonOpen"
      :officer="officer"
      :currentGroup="currentGroup"
      @editPerson="_editPerson"
      @close="prsonClose"
      @submit="confirmBtnPersonBtn"
    ></AuthorizedOfficerDialog>
    <!-- E 关联人员弹窗组件 -->
  </div>
</template>

<script setup name="groupFile">
import AddGroup from './addGroup.vue'
import EditGroupDialog from './editGroupDialog.vue'
import AuthorizedOfficerDialog from './authorizedOfficerDialog.vue'
import DocCateDialog from './docCateDialog.vue'
import {
  getGroupList,
  deleteGroupById,
  getGroupDetail,
  updateGroup,
  getGroupTree,
  updateGroupPerson,
  updateGroupCate,
} from '@/api/fileManager'
import { handleTree } from '@/utils/index'
const { proxy } = getCurrentInstance()

let currentSetp = ref(1) // 当前触发按钮
let currentGroup = ref({})
const stepMap = reactive({
  add: 0,
  edit: 1,
  cate: 2,
  person: 3,
})
const drawer = ref(false)
function addGroupClose() {
  drawer.value = false
}
const cateOpen = ref(false)
const groupTree = ref([]) // 树形类别
const groupTreeCheck = ref([]) // 选中的类别
const groupList = ref([]) // 所有类别
let prsonOpen = ref(false)
const officer = ref({})
const editPerson = ref([])
let groupOpen = ref(false)
const cateOptions = ref(undefined) // 文档目录
const _checkedNodes = ref([])
const formObj = ref({})
// 过滤相关配置
const filterInfo = ref({
  query: {},
  copyQuery: {},
  list: [
    {
      componentType: 'input',
      label: '权限组名称',
      value: 'filePortfolioNameLike',
      event: search,
    },
  ],
  btn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  btnList: [
    {
      type: 'button',
      label: '新增',
      event: addCate,
      show: proxy.$permission('groupFile:add'),
    },
    // {
    //   type: 'slot',
    //   value: 'del',
    //   show: proxy.$permission('groupFile:del'),
    // },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  api: getGroupList,
  data: [{}],
  selections: [],
  fieldList: [
    {
      label: '权限组名称',
      value: 'filePortfolioName',
    },
    { label: '授权说明', value: 'authorizationInstructions' },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '120',
    btList: [
      {
        label: '编辑',
        event: update,
        show: proxy.$permission('groupFile:update'),
      },
      {
        label: '文档目录',
        event: fileCate,
        show: proxy.$permission('groupFile:fileCate'),
      },
      {
        label: '关联人员',
        event: filePerson,
        show: proxy.$permission('groupFile:person'),
      },
      {
        label: '删除',
        event: del,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: proxy.$permission('groupFile:del'),
      },
    ],
  },
})
const canDelete = computed(() => {
  return tableInfo.value.selections.length
})

onMounted(() => {
  filterInfo.value.copyQuery = proxy.$fn.deepClone(filterInfo.value.query)
})

// 搜索
function search() {
  // 重置分页
  tableInfo.value.initCurpage = Math.random()
  tableInfo.value.refresh = Math.random()
}
function clearSearch() {
  filterInfo.value.query = proxy.$fn.deepClone(filterInfo.value.copyQuery)
  search()
}
function addCate() {
  drawer.value = true
  currentSetp.value = stepMap.add
}
function fileCate(val) {
  currentGroup.value = val
  cateOpen.value = true
  // 文档目录授权
  groupTreeCheck.value = []
  _getGroupTree(currentGroup.value.id)
}
//删除
function del(row = undefined) {
  const ids = _getIds(row)
  deleteGroupById(ids).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
function _getIds(row) {
  let ids = []
  if (row && row.id) {
    ids = [row.id]
  } else {
    if (tableInfo.value.selections.length > 0) {
      ids = tableInfo.value.selections.map((row) => row.id)
    }
  }
  return ids
}
function update(val) {
  // 编辑设置数据
  currentGroup.value = val
  setFormValue()
  groupOpen.value = true
}
function filePerson(val) {
  currentGroup.value = val
  prsonOpen.value = true
  currentGroup.value = val
  // 查询权限组已授权人员
  _getGroupDetail(currentGroup.value.id)
}
/** 获取类别下拉树结构 */
function _getGroupTree(id) {
  getGroupTree(id).then((response) => {
    let fileCategoryList = response.data.fileCategoryList
    fileCategoryList.forEach((element) => {
      element['allowDownloads'] = '0'
      element['allowUpload'] = '0'
      element['allowView'] = '0'
      element['allowPreview'] = '0'
      // element['allowDeleted'] = '0'
      element['allowPrint'] = '0'
    })
    groupList.value = fileCategoryList
    groupTree.value = handleTree(response.data.fileCategoryList, 'id')
    groupTreeCheck.value = response.data.fileCategoryPortfolioMapperList
  })
}
// 编辑文档权限组按钮
function confirmBtnCate() {
  // 编辑权限组名称和授权说明
  editCate()
}
// 提交修改文档权限组信息
function editCate() {
  let paramsArr = []
  _checkedNodes.value.forEach((element) => {
    const params = {
      allowDownloads: element.allowDownloads,
      allowUpload: element.allowUpload,
      allowView: element.allowView,
      allowPreview: element.allowPreview,
      // allowDeleted: element.allowDeleted,
      allowPrint: element.allowPrint,
      fileCategoryId: element.id,
      authorizationInstructions: element.categoryName,
      filePortfolioId: currentGroup.value.id,
      filePortfolioName: currentGroup.value.filePortfolioName,
    }
    paramsArr.push(params)
  })
  _updateGroupCate(paramsArr)
}
function _checkChange(checkedNodes) {
  _checkedNodes.value = checkedNodes
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
// 编辑文档权限组
function _updateGroupCate(params) {
  const paramsData = {
    portfolioId: currentGroup.value.id,
    entityList: params,
  }
  updateGroupCate(paramsData).then((res) => {
    if (res.success) {
      cateClose()
      refresh()
      showTip()
    }
  })
}
function cateClose() {
  cateOpen.value = false
  proxy.$refs.docCateDialog.$refs.groupRef.resetCate()
}
// 查询权限组已授权人员
function _getGroupDetail(id) {
  getGroupDetail(id).then((res) => {
    officer.value = res.data
  })
}
function _editPerson(val) {
  // 编辑关联人员
  editPerson.value = val
}
// 修改关联人员按钮
function confirmBtnPersonBtn() {
  _updateGroupPerson(editPerson.value)
}
// 权限组中修改人员
function _updateGroupPerson(data) {
  const params = {
    entityList: data,
    portfolioId: currentGroup.value.id,
  }
  updateGroupPerson(params).then((res) => {
    prsonOpen.value = false
    refresh()
  })
}
function prsonClose() {
  prsonOpen.value = false
}
// 请求列表方法
function getList() {
  // 加载中
  tableInfo.value.refresh = Math.random()
}
function refresh() {
  drawer.value = false
  getList()
}
function refreshList() {
  getList()
}
function groupClose() {
  groupOpen.value = false
}
// 编辑文档权限组按钮
function confirmBtn() {
  // 编辑权限组名称和授权说明
  editInfo()
}
// 提交修改文档权限组信息
function editInfo() {
  const params = {
    id: currentGroup.value.id,
    filePortfolioName: formObj.value['filePortfolioName'],
    authorizationInstructions: formObj.value['authorizationInstructions'],
  }
  _updateGroup(params)
}
// 编辑文档权限组
function _updateGroup(params) {
  updateGroup(params).then((res) => {
    if (res.success) {
      groupOpen.value = false
      refresh()
      showTip()
    }
  })
}
function showTip() {
  proxy.$message.success({
    message: '操作成功',
    showClose: true,
    duration: 3500,
  })
}
function setFormValue() {
  formObj.value = {
    filePortfolioName: currentGroup.value['filePortfolioName'],
    authorizationInstructions: currentGroup.value['authorizationInstructions'],
  }
}
</script>
